package com.gs.disk.service.common;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gs.common.util.FileUtils;
import com.gs.disk.dao.common.OssDao;
import com.gs.disk.entity.OssEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;

/**
 * @title: 孙杨申
 * @date 2022/6/5 14:09
 */

@Service
public class OssService {

    @Resource
    private OssDao dao;

    @Resource
    private MinioService minioService;

    /**
     * 获取文件对象信息
     * @param id
     * @return
     */
    public OssEntity get(Long id) {
        OssEntity ossEntity = dao.selectById(id);
        return ossEntity;
    }

    /**
     * 上传文件返回id
     * @param entity oss文件对象
     * @return
     */
    public Long insert(OssEntity entity) {
        String path = entity.getPath();
        // 上传文件的path必须以“/”结尾
        if(path != null && !path.endsWith("/")) {
            path += "/";
            entity.setPath(path);
        }
        dao.insert(entity);
        return entity.getId();
    }

    /**
     * 获取文件url
     * @param id oss文件id
     * @return
     */
    public String getUrl(Long id) {
        QueryWrapper<OssEntity> wrapper = new QueryWrapper<>();
        wrapper.select("path");
        wrapper.select("file_name");
        OssEntity ossEntity = dao.selectOne(wrapper);
        return ossEntity.getPath() + ossEntity.getOssFileName();
    }

    /**
     * 查询文件列表
     * @param path 文件路径
     * @return
     */
    public List<OssEntity> list(String path) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("path", path);
        List list = dao.selectList(wrapper);
        return list;
    }

    /**
     * 获取下载url
     * @param id
     * @return
     */
    public String getDownloadURL(Long id) {
        OssEntity ossEntity = dao.selectById(id);
//        if(ObjectUtil.isNull(ossEntity)) {
//            return "parser-error:" + id;
//        }
        return minioService.getDownloadURL(ossEntity.getBucket(), ossEntity.getPath() + ossEntity.getOssFileName());
    }

    /**
     * 获取文件对象
     * @param id
     * @return
     * @throws Exception
     */
    public InputStream getObject(Long id) throws Exception {
        OssEntity ossEntity = dao.selectById(id);
        return minioService.getObject(ossEntity.getPath() + ossEntity.getOssFileName());
    }
}
